package com.egs.witzbackend.game;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import com.egs.witzbackend.domain.Counter;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class CounterService {
	private PersistenceManagerFactory PMF;
	
	public CounterService (PersistenceManagerFactory PMF) {
		this.PMF = PMF;
	}

	public Integer getMainCount() {
		PersistenceManager pm = PMF.getPersistenceManager();
		
		Key k = KeyFactory.createKey(Counter.class.getSimpleName(), "main_counter");
		
		Counter mainCounter = null;
		try {
			mainCounter = pm.getObjectById(Counter.class, k);
		} catch (JDOObjectNotFoundException e) {
			mainCounter = new Counter();
			mainCounter.setKey(k);
			pm.makePersistent(mainCounter);
		} finally {
            pm.close();
        }
		
		return mainCounter.getCount();
	}
	
	public void IncrementMainCount() {
		PersistenceManager pm = PMF.getPersistenceManager();
		
		Key k = KeyFactory.createKey(Counter.class.getSimpleName(), "main_counter");
		
		Counter mainCounter = null;
		try {
			mainCounter = pm.getObjectById(Counter.class, k);
			mainCounter.incrementCount();
			pm.makePersistent(mainCounter);
		} catch (JDOObjectNotFoundException e) {
			
		} finally {
            pm.close();
        }
		
	}
	
}
